package com.ffapp.demo.util.update;

import android.app.Application;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ffapp.demo.R;
import com.ffapp.demo.basis.BasisActivity;
import com.ffapp.demo.basis.BasisApp;
import com.ffapp.demo.util.MyUtils;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.entity.UpdateEntity;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import my.MD5;
import my.SystemParamsUtils;
import my.http.MyParams;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/***
 * 更新
 * 请在 build.gradle 中加入两行
 * implementation 'com.github.xuexiangjys:XUpdate:1.1.4'
 * implementation 'com.zhy:okhttputils:2.6.2'
 *
 * 在application中初始化  UpdateUtil.initXUpdate(this);
 *
 * 下面参数 URL_UPDATE、AUTH_APP_ID、AUTH_APP_KEY 应该不用变，
 * APP_ID 在应用管理后台中添加应用时生成
 *
 *
 * xupdate_bg_app_top_blue 头部图片文件应放再hdpi目录里
 * */
public class UpdateUtil {
//    public static final String TAG = UpdateUtil.class.getSimpleName();
    public static final String TAG = "FOUR-FAITH";
    public static final String URL_UPDATE = "http://app.ff-cloud.net/api.php/app/newest";
    public static final String AUTH_APP_ID = "159004459760";
    public static final String AUTH_APP_KEY  = "LUrsFDXpFhcjcumF";

    public static final String APP_ID = "bd16ead2-cc45-5cf0-6ae3-355e156ff75e";

    public static void initXUpdate(Application application) {
        XUpdate.get()
                .debug(true)
                .isWifiOnly(false)                                               //默认设置只在wifi下检查版本更新
                .isGet(false)                                                    //默认设置使用get请求检查版本
                .isAutoMode(false)                                              //默认设置非自动模式，可根据具体使用配置
                .setIUpdateHttpService(new OKHttpUpdateHttpService())           //这个必须设置！实现网络请求功能。
                .init(application);
    }


    private static String getSecretStr(ArrayList<String> list) {
        String result = "";
        Collections.sort(list);
        StringBuilder builder = new StringBuilder();
        for(String data:list){
//            LogUtil.i(""+data);
            builder.append(data).append("&");
        }
        builder.append("appkey="+AUTH_APP_KEY);
//        LogUtil.i("字符串"+builder.toString());
        result = MD5.getMD5ofStrLowercase(builder.toString()).substring(0,32);

//        if(result.length()> 48){
//            result = result.substring(0,48).toUpperCase();
//        }
//            LogUtil.i("签名值"+result);
        return result;
    }

    private static void AddHeaderToBuilder(Request.Builder build, MyParams myParams, boolean isGet){
        long time = new Date().getTime()/1000;
        build.addHeader("APP-ID", AUTH_APP_ID);
        build.addHeader("APP-AUTHTIME", time + "");
        build.addHeader("APP-VERSION", SystemParamsUtils.getAPPVersonCode(BasisApp.mContext)+"");
        build.addHeader("APP-TYPE",  "android");
        build.addHeader("APP-IMEI",  MyUtils.getIMEI());
        build.addHeader("APP-DEVICE",
                SystemParamsUtils.getPhoneModel() + "");
//        build.addHeader("APP-TOKEN", LoginBean.getUserToken());
        build.addHeader("APP-TOKEN","");
        ArrayList<String> listP = new ArrayList<>();
        listP.add("header_app_id="+AUTH_APP_ID);
//        listP.add("app_key="+HEADER_HTTP_AuthKey);
//        listP.add("header_app_token="+LoginBean.getUserToken());
        listP.add("header_app_token="+"");
        listP.add("header_app_authtime="+time+"");
        if(isGet){
            if(myParams !=null){
//                String[] pramsStrs = myParams.getListKeyValueList().split("&");
                for(String key:myParams.getUrlParams().keySet()){
//			builder.add(key,urlParams.get(key));
                    listP.add(key+"="+myParams.getUrlParams().get(key));
                }
//                for(String data:pramsStrs){
//                    if(data.startsWith("file["))continue;
//                    if(data.startsWith("uploadFile"))continue;
////                listP.add(data.substring(data.indexOf("=")+1));
//                    listP.add(data);
//                }
            }
        }

        build.addHeader("APP-SIGN",getSecretStr(listP));
    }
    public static void checkUpdate(final BasisActivity mContext, final boolean isShowToast){
        if(isShowToast){
            mContext.showLoading();
        }
        OkHttpClient okHttpClient = new  OkHttpClient.Builder().build();
        MyParams myParams = new MyParams();
        myParams.put("app_id",APP_ID);
        Request.Builder buildRquest = new Request.Builder()
                .url(URL_UPDATE)
//                .url(URL_UPDATE+"app_id="+APP_ID)
                .post(myParams.getRequestBody());
        AddHeaderToBuilder(buildRquest,myParams,false);
        Request request = buildRquest.build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                if(isShowToast){
                    BasisApp.showToast("接口访问失败");
                    mContext.hideLoading();
                }
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                String jsonResult = response.body().string()+"";
                Log.d(TAG, "onResponse: " + jsonResult);
                if(!jsonResult.startsWith("{")){
                    BasisApp.showToast("接口返回数据有误");
                    mContext.hideLoading();
                    return;
                }
                JSONObject jsonObject = JSON.parseObject(jsonResult);
                if(jsonObject.getInteger("status") != 200){
                    BasisApp.showToast("接口返回数据有误");
                    mContext.hideLoading();
                    return;
                }
                UpdateBean updateBean = JSON.parseObject(jsonObject.getString("result"),UpdateBean.class);
                if(!updateBean.isNeedUpdate(mContext)){
                    BasisApp.showToast("已是最新版本");
                    mContext.hideLoading();
                    return;
                }
                UpdateEntity updateEntity = new UpdateEntity()
                        .setHasUpdate(updateBean.isNeedUpdate(mContext))
                        .setForce(updateBean.getIs_forced_upgradeBoolean())
//                        .setIsIgnorable(updateBean.getIs_forced_upgradeBoolean())
                        .setVersionCode(updateBean.getNumber())
                        .setVersionName(updateBean.getName())
                        .setUpdateContent(updateBean.getInfo())
                        .setDownloadUrl(updateBean.getUrl())
//                        .setDownloadUrl("https://ugc-download-4.imfir.cn/7257bfd68934ef98eb47f93d218caa934d195800.apk?auth_key=1590048176-0-0-0b5cfbb1355b86d9407472e5f1b85bb8")
//                        .setSize(result.apkSize)
                        ;
                XUpdate.newBuild(mContext)
                        .promptThemeColor(mContext.getResources().getColor(R.color.base_blue))
                        .promptTopResId(R.drawable.xupdate_bg_app_top_blue)
                        .build().update(updateEntity);
                if(isShowToast){
                    mContext.hideLoading();
                }
            }
        });

    }

}
